#include <iostream>
using namespace std;
#include <unistd.h>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <strings.h>

namespace Client
{
    class udpClient
    {
    public:
        udpClient(const string &ip, const uint16_t &port) : _sock(-1), _serverip(ip), _serverport(port)
        {
        }

        void initClient()
        {
            _sock = socket(AF_INET, SOCK_DGRAM, 0); // 面向数据报
            if (_sock < 0)
            {
                perror("sock errno");
                exit(1);
            }
            printf("socket success\n");
            cout << "sockfd:" << _sock << endl;
        }

        void run()
        {
            // 业务处理
            sockaddr_in server;
            bzero(&server, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_port = htons(_serverport);
            server.sin_addr.s_addr = inet_addr(_serverip.c_str());

            string message;
            while (1)
            {
                cout << "请输入#";
                cin >> message;
                sendto(_sock, message.c_str(), message.size(), 0, (sockaddr *)&server, sizeof(server));

                char buffer[1024];
                sockaddr_in temp;
                socklen_t len = sizeof(temp);
                int n = recvfrom(_sock, buffer, sizeof(buffer) - 1, 0, (sockaddr *)&temp, &len);
                if (n > 0)
                {
                    buffer[n] = 0;
                    cout << "服务器翻译的结果#" << buffer << endl;
                }

                // 还要接收服务器的信息
                //  int n = recv(_sock,buffer,sizeof(buffer)-1,0);
                //  if(n > 0){
                //      buffer[n] = 0;
                //      cout<<buffer<<endl;
                //  }
            }
        }

        ~udpClient()
        {
        }

    private:
        int _sock;
        string _serverip;
        uint16_t _serverport;
    };
}